"""
用户行为记录服务实现

提供用户行为数据收集和分析功能，包括：
- 行为数据收集和存储
- 隐私保护机制
- 行为模式分析
- 个性化洞察生成
"""
import hashlib
import json
from typing import List, Dict, Any, Optional, Set
from datetime import datetime, timedelta
from dataclasses import asdict
from collections import defaultdict, Counter

from ..models.analysis_models import UserBehavior, UserPreferences


class UserBehaviorService:
    """用户行为记录服务"""
    
    def __init__(self):
        # 行为数据存储（内存中，实际应用中应使用数据库）
        self.behavior_data: Dict[str, List[UserBehavior]] = defaultdict(list)
        self.user_sessions: Dict[str, Dict[str, Any]] = {}
        
        # 隐私保护配置
        self.privacy_config = {
            'anonymize_user_ids': True,
            'data_retention_days': 90,
            'sensitive_fields': ['user_feedback', 'context'],
            'hash_salt': 'research_automation_salt_2024'
        }
        
        # 行为分类定义
        self.behavior_categories = {
            'navigation': ['page_view', 'menu_click', 'tab_switch'],
            'research_activity': ['topic_analysis', 'literature_search', 'experiment_design'],
            'quality_improvement': ['quality_assessment', 'issue_detection', 'improvement_suggestion'],
            'collaboration': ['document_edit', 'comment_add', 'version_save'],
            'system_interaction': ['login', 'logout', 'settings_change', 'help_view']
        }
        
        # 行为模式定义
        self.behavior_patterns = {
            'frequent_user': {'min_sessions_per_week': 5, 'min_actions_per_session': 10},
            'power_user': {'min_unique_features': 8, 'min_advanced_actions': 20},
            'collaborative_user': {'min_collaboration_actions': 15},
            'quality_focused': {'min_quality_actions': 10},
            'research_intensive': {'min_research_actions': 25}
        }
    
    async def record_behavior(self, user_id: str, action_type: str, 
                            context: Optional[Dict[str, Any]] = None,
                            duration_seconds: float = 0.0,
                            success: bool = True,
                            user_feedback: Optional[str] = None) -> bool:
        """记录用户行为"""
        try:
            # 应用隐私保护
            protected_user_id = await self._protect_user_id(user_id)
            protected_context = await self._protect_sensitive_data(context or {})
            protected_feedback = await self._protect_sensitive_data({'feedback': user_feedback or ''})
            
            # 创建行为记录
            behavior = UserBehavior(
                action_type=action_type,
                context=protected_context,
                duration_seconds=duration_seconds,
                success=success,
                user_feedback=protected_feedback.get('feedback')
            )
            
            # 存储行为数据
            self.behavior_data[protected_user_id].append(behavior)
            
            # 更新会话信息
            await self._update_session_info(protected_user_id, action_type)
            
            # 清理过期数据
            await self._cleanup_expired_data(protected_user_id)
            
            return True
            
        except Exception as e:
            print(f"记录用户行为失败: {e}")
            return False
    
    async def _protect_user_id(self, user_id: str) -> str:
        """保护用户ID"""
        if self.privacy_config['anonymize_user_ids']:
            # 使用哈希函数匿名化用户ID
            salt = self.privacy_config['hash_salt']
            return hashlib.sha256(f"{user_id}{salt}".encode()).hexdigest()[:16]
        return user_id
    
    async def _protect_sensitive_data(self, data: Dict[str, Any]) -> Dict[str, Any]:
        """保护敏感数据"""
        protected_data = data.copy()
        
        for field in self.privacy_config['sensitive_fields']:
            if field in protected_data:
                value = protected_data[field]
                if isinstance(value, str) and len(value) > 50:
                    # 截断长文本
                    protected_data[field] = value[:50] + "..."
                elif isinstance(value, dict):
                    # 移除可能的敏感键
                    sensitive_keys = ['password', 'token', 'email', 'phone']
                    for key in sensitive_keys:
                        if key in value:
                            protected_data[field][key] = "[PROTECTED]"
        
        return protected_data
    
    async def _update_session_info(self, user_id: str, action_type: str):
        """更新会话信息"""
        current_time = datetime.now()
        
        if user_id not in self.user_sessions:
            self.user_sessions[user_id] = {
                'start_time': current_time,
                'last_activity': current_time,
                'action_count': 0,
                'unique_actions': set()
            }
        
        session = self.user_sessions[user_id]
        session['last_activity'] = current_time
        session['action_count'] += 1
        session['unique_actions'].add(action_type)
    
    async def _cleanup_expired_data(self, user_id: str):
        """清理过期数据"""
        retention_days = self.privacy_config['data_retention_days']
        cutoff_date = datetime.now() - timedelta(days=retention_days)
        
        if user_id in self.behavior_data:
            # 过滤掉过期的行为记录
            self.behavior_data[user_id] = [
                behavior for behavior in self.behavior_data[user_id]
                if behavior.created_at > cutoff_date
            ]
    
    async def get_user_behavior_summary(self, user_id: str, 
                                      days: int = 30) -> Dict[str, Any]:
        """获取用户行为摘要"""
        try:
            protected_user_id = await self._protect_user_id(user_id)
            
            if protected_user_id not in self.behavior_data:
                return {'error': '用户行为数据不存在'}
            
            # 获取指定时间范围内的行为数据
            cutoff_date = datetime.now() - timedelta(days=days)
            recent_behaviors = [
                behavior for behavior in self.behavior_data[protected_user_id]
                if behavior.created_at > cutoff_date
            ]
            
            if not recent_behaviors:
                return {'error': '指定时间范围内无行为数据'}
            
            # 计算摘要统计
            summary = {
                'total_actions': len(recent_behaviors),
                'unique_action_types': len(set(b.action_type for b in recent_behaviors)),
                'success_rate': sum(1 for b in recent_behaviors if b.success) / len(recent_behaviors),
                'average_duration': sum(b.duration_seconds for b in recent_behaviors) / len(recent_behaviors),
                'most_common_actions': [],
                'activity_by_category': {},
                'daily_activity': {},
                'session_info': self.user_sessions.get(protected_user_id, {})
            }
            
            # 最常见的行为
            action_counts = Counter(b.action_type for b in recent_behaviors)
            summary['most_common_actions'] = action_counts.most_common(5)
            
            # 按类别统计活动
            for category, actions in self.behavior_categories.items():
                category_count = sum(1 for b in recent_behaviors if b.action_type in actions)
                summary['activity_by_category'][category] = category_count
            
            # 按日统计活动
            daily_counts = defaultdict(int)
            for behavior in recent_behaviors:
                date_key = behavior.created_at.strftime('%Y-%m-%d')
                daily_counts[date_key] += 1
            summary['daily_activity'] = dict(daily_counts)
            
            return summary
            
        except Exception as e:
            print(f"获取用户行为摘要失败: {e}")
            return {'error': '获取行为摘要失败'}
    
    async def analyze_behavior_patterns(self, user_id: str) -> Dict[str, Any]:
        """分析用户行为模式"""
        try:
            protected_user_id = await self._protect_user_id(user_id)
            
            if protected_user_id not in self.behavior_data:
                return {'error': '用户行为数据不存在'}
            
            behaviors = self.behavior_data[protected_user_id]
            
            if len(behaviors) < 10:  # 需要足够的数据进行分析
                return {'error': '行为数据不足，无法进行模式分析'}
            
            patterns = {
                'user_type': await self._classify_user_type(behaviors),
                'usage_patterns': await self._analyze_usage_patterns(behaviors),
                'preference_indicators': await self._extract_preference_indicators(behaviors),
                'efficiency_metrics': await self._calculate_efficiency_metrics(behaviors),
                'learning_curve': await self._analyze_learning_curve(behaviors)
            }
            
            return patterns
            
        except Exception as e:
            print(f"分析行为模式失败: {e}")
            return {'error': '行为模式分析失败'}
    
    async def _classify_user_type(self, behaviors: List[UserBehavior]) -> List[str]:
        """分类用户类型"""
        user_types = []
        
        # 计算各种指标
        total_behaviors = len(behaviors)
        unique_actions = len(set(b.action_type for b in behaviors))
        
        # 按类别统计行为
        category_counts = defaultdict(int)
        for behavior in behaviors:
            for category, actions in self.behavior_categories.items():
                if behavior.action_type in actions:
                    category_counts[category] += 1
        
        # 计算会话统计
        sessions_per_week = self._estimate_sessions_per_week(behaviors)
        actions_per_session = total_behaviors / max(1, sessions_per_week)
        
        # 应用分类规则
        for pattern_name, criteria in self.behavior_patterns.items():
            if pattern_name == 'frequent_user':
                if (sessions_per_week >= criteria['min_sessions_per_week'] and 
                    actions_per_session >= criteria['min_actions_per_session']):
                    user_types.append('frequent_user')
            
            elif pattern_name == 'power_user':
                if (unique_actions >= criteria['min_unique_features'] and
                    total_behaviors >= criteria['min_advanced_actions']):
                    user_types.append('power_user')
            
            elif pattern_name == 'collaborative_user':
                collab_actions = category_counts.get('collaboration', 0)
                if collab_actions >= criteria['min_collaboration_actions']:
                    user_types.append('collaborative_user')
            
            elif pattern_name == 'quality_focused':
                quality_actions = category_counts.get('quality_improvement', 0)
                if quality_actions >= criteria['min_quality_actions']:
                    user_types.append('quality_focused')
            
            elif pattern_name == 'research_intensive':
                research_actions = category_counts.get('research_activity', 0)
                if research_actions >= criteria['min_research_actions']:
                    user_types.append('research_intensive')
        
        return user_types if user_types else ['casual_user']
    
    def _estimate_sessions_per_week(self, behaviors: List[UserBehavior]) -> float:
        """估算每周会话数"""
        if not behaviors:
            return 0
        
        # 简化实现：基于行为时间间隔估算会话
        sorted_behaviors = sorted(behaviors, key=lambda x: x.created_at)
        
        sessions = 1
        last_time = sorted_behaviors[0].created_at
        
        for behavior in sorted_behaviors[1:]:
            # 如果两个行为间隔超过30分钟，认为是新会话
            if (behavior.created_at - last_time).total_seconds() > 1800:
                sessions += 1
            last_time = behavior.created_at
        
        # 计算时间跨度（周）
        time_span = (sorted_behaviors[-1].created_at - sorted_behaviors[0].created_at).days / 7
        time_span = max(1, time_span)  # 至少1周
        
        return sessions / time_span
    
    async def _analyze_usage_patterns(self, behaviors: List[UserBehavior]) -> Dict[str, Any]:
        """分析使用模式"""
        patterns = {}
        
        # 时间模式分析
        hour_counts = defaultdict(int)
        day_counts = defaultdict(int)
        
        for behavior in behaviors:
            hour_counts[behavior.created_at.hour] += 1
            day_counts[behavior.created_at.strftime('%A')] += 1
        
        patterns['peak_hours'] = sorted(hour_counts.items(), key=lambda x: x[1], reverse=True)[:3]
        patterns['active_days'] = sorted(day_counts.items(), key=lambda x: x[1], reverse=True)[:3]
        
        # 功能使用模式
        feature_usage = defaultdict(int)
        for behavior in behaviors:
            feature_usage[behavior.action_type] += 1
        
        patterns['top_features'] = sorted(feature_usage.items(), key=lambda x: x[1], reverse=True)[:5]
        
        # 会话长度模式
        session_durations = []
        current_session_start = None
        
        for behavior in sorted(behaviors, key=lambda x: x.created_at):
            if current_session_start is None:
                current_session_start = behavior.created_at
            elif (behavior.created_at - current_session_start).total_seconds() > 1800:
                # 新会话开始
                current_session_start = behavior.created_at
            else:
                # 会话持续
                duration = (behavior.created_at - current_session_start).total_seconds() / 60
                session_durations.append(duration)
        
        if session_durations:
            patterns['average_session_duration'] = sum(session_durations) / len(session_durations)
            patterns['max_session_duration'] = max(session_durations)
        
        return patterns
    
    async def _extract_preference_indicators(self, behaviors: List[UserBehavior]) -> Dict[str, Any]:
        """提取偏好指标"""
        preferences = {}
        
        # 功能偏好
        feature_frequency = defaultdict(int)
        feature_success = defaultdict(list)
        
        for behavior in behaviors:
            feature_frequency[behavior.action_type] += 1
            feature_success[behavior.action_type].append(behavior.success)
        
        # 计算偏好分数（频率 × 成功率）
        preference_scores = {}
        for feature, frequency in feature_frequency.items():
            success_rate = sum(feature_success[feature]) / len(feature_success[feature])
            preference_scores[feature] = frequency * success_rate
        
        preferences['preferred_features'] = sorted(
            preference_scores.items(), key=lambda x: x[1], reverse=True
        )[:5]
        
        # 工作流偏好
        action_sequences = []
        sorted_behaviors = sorted(behaviors, key=lambda x: x.created_at)
        
        for i in range(len(sorted_behaviors) - 1):
            current_action = sorted_behaviors[i].action_type
            next_action = sorted_behaviors[i + 1].action_type
            time_gap = (sorted_behaviors[i + 1].created_at - sorted_behaviors[i].created_at).total_seconds()
            
            # 如果时间间隔小于5分钟，认为是连续操作
            if time_gap < 300:
                action_sequences.append((current_action, next_action))
        
        sequence_counts = Counter(action_sequences)
        preferences['common_workflows'] = sequence_counts.most_common(5)
        
        return preferences
    
    async def _calculate_efficiency_metrics(self, behaviors: List[UserBehavior]) -> Dict[str, float]:
        """计算效率指标"""
        metrics = {}
        
        # 成功率
        total_actions = len(behaviors)
        successful_actions = sum(1 for b in behaviors if b.success)
        metrics['success_rate'] = successful_actions / total_actions if total_actions > 0 else 0
        
        # 平均操作时间
        durations = [b.duration_seconds for b in behaviors if b.duration_seconds > 0]
        metrics['average_action_duration'] = sum(durations) / len(durations) if durations else 0
        
        # 操作速度趋势（最近的操作是否更快）
        if len(durations) >= 10:
            recent_durations = durations[-5:]
            early_durations = durations[:5]
            
            recent_avg = sum(recent_durations) / len(recent_durations)
            early_avg = sum(early_durations) / len(early_durations)
            
            metrics['speed_improvement'] = (early_avg - recent_avg) / early_avg if early_avg > 0 else 0
        
        # 错误率趋势
        failed_actions = [b for b in behaviors if not b.success]
        if len(behaviors) >= 20:
            recent_behaviors = behaviors[-10:]
            early_behaviors = behaviors[:10]
            
            recent_error_rate = sum(1 for b in recent_behaviors if not b.success) / len(recent_behaviors)
            early_error_rate = sum(1 for b in early_behaviors if not b.success) / len(early_behaviors)
            
            metrics['error_rate_improvement'] = early_error_rate - recent_error_rate
        
        return metrics
    
    async def _analyze_learning_curve(self, behaviors: List[UserBehavior]) -> Dict[str, Any]:
        """分析学习曲线"""
        learning_curve = {}
        
        if len(behaviors) < 20:
            return {'error': '数据不足以分析学习曲线'}
        
        # 按时间分组分析
        sorted_behaviors = sorted(behaviors, key=lambda x: x.created_at)
        group_size = len(sorted_behaviors) // 5  # 分成5组
        
        groups = []
        for i in range(0, len(sorted_behaviors), group_size):
            group = sorted_behaviors[i:i + group_size]
            if group:
                groups.append(group)
        
        # 分析每组的指标
        group_metrics = []
        for i, group in enumerate(groups):
            success_rate = sum(1 for b in group if b.success) / len(group)
            avg_duration = sum(b.duration_seconds for b in group if b.duration_seconds > 0) / len(group)
            unique_actions = len(set(b.action_type for b in group))
            
            group_metrics.append({
                'period': i + 1,
                'success_rate': success_rate,
                'average_duration': avg_duration,
                'unique_actions': unique_actions,
                'total_actions': len(group)
            })
        
        learning_curve['progression'] = group_metrics
        
        # 计算学习趋势
        success_rates = [g['success_rate'] for g in group_metrics]
        durations = [g['average_duration'] for g in group_metrics if g['average_duration'] > 0]
        
        if len(success_rates) >= 3:
            # 简单线性趋势分析
            success_trend = (success_rates[-1] - success_rates[0]) / len(success_rates)
            learning_curve['success_trend'] = 'improving' if success_trend > 0.05 else 'stable' if success_trend > -0.05 else 'declining'
        
        if len(durations) >= 3:
            duration_trend = (durations[-1] - durations[0]) / len(durations)
            learning_curve['efficiency_trend'] = 'improving' if duration_trend < -0.5 else 'stable' if duration_trend < 0.5 else 'declining'
        
        return learning_curve
    
    async def generate_behavior_insights(self, user_id: str) -> List[str]:
        """生成行为洞察"""
        try:
            protected_user_id = await self._protect_user_id(user_id)
            
            if protected_user_id not in self.behavior_data:
                return ["无用户行为数据"]
            
            behaviors = self.behavior_data[protected_user_id]
            insights = []
            
            # 基本统计洞察
            total_actions = len(behaviors)
            if total_actions > 100:
                insights.append(f"您是活跃用户，已执行{total_actions}次操作")
            elif total_actions > 50:
                insights.append(f"您是中等活跃用户，已执行{total_actions}次操作")
            else:
                insights.append(f"您的使用频率较低，已执行{total_actions}次操作")
            
            # 成功率洞察
            success_rate = sum(1 for b in behaviors if b.success) / len(behaviors)
            if success_rate > 0.9:
                insights.append("您的操作成功率很高，说明对系统使用熟练")
            elif success_rate < 0.7:
                insights.append("建议查看帮助文档以提高操作成功率")
            
            # 功能使用洞察
            action_counts = Counter(b.action_type for b in behaviors)
            most_used = action_counts.most_common(1)[0]
            insights.append(f"您最常使用的功能是'{most_used[0]}'，使用了{most_used[1]}次")
            
            # 时间模式洞察
            hour_counts = defaultdict(int)
            for behavior in behaviors:
                hour_counts[behavior.created_at.hour] += 1
            
            peak_hour = max(hour_counts.items(), key=lambda x: x[1])[0]
            if 9 <= peak_hour <= 17:
                insights.append("您主要在工作时间使用系统")
            elif 18 <= peak_hour <= 22:
                insights.append("您经常在晚上使用系统")
            else:
                insights.append("您的使用时间比较灵活")
            
            # 学习进展洞察
            if len(behaviors) >= 20:
                recent_behaviors = behaviors[-10:]
                early_behaviors = behaviors[:10]
                
                recent_success = sum(1 for b in recent_behaviors if b.success) / len(recent_behaviors)
                early_success = sum(1 for b in early_behaviors if b.success) / len(early_behaviors)
                
                if recent_success > early_success + 0.1:
                    insights.append("您的操作熟练度在不断提升")
                elif recent_success < early_success - 0.1:
                    insights.append("建议复习基础操作以提高效率")
            
            return insights
            
        except Exception as e:
            print(f"生成行为洞察失败: {e}")
            return ["无法生成行为洞察"]
    
    async def export_user_data(self, user_id: str, include_sensitive: bool = False) -> Dict[str, Any]:
        """导出用户数据（用于数据可携带性）"""
        try:
            protected_user_id = await self._protect_user_id(user_id)
            
            if protected_user_id not in self.behavior_data:
                return {'error': '用户数据不存在'}
            
            behaviors = self.behavior_data[protected_user_id]
            
            export_data = {
                'user_id': protected_user_id,
                'export_date': datetime.now().isoformat(),
                'total_behaviors': len(behaviors),
                'data_retention_policy': f"{self.privacy_config['data_retention_days']} days",
                'behaviors': []
            }
            
            for behavior in behaviors:
                behavior_data = {
                    'action_type': behavior.action_type,
                    'timestamp': behavior.created_at.isoformat(),
                    'duration_seconds': behavior.duration_seconds,
                    'success': behavior.success
                }
                
                # 根据权限决定是否包含敏感数据
                if include_sensitive:
                    behavior_data['context'] = behavior.context
                    behavior_data['user_feedback'] = behavior.user_feedback
                
                export_data['behaviors'].append(behavior_data)
            
            return export_data
            
        except Exception as e:
            print(f"导出用户数据失败: {e}")
            return {'error': '数据导出失败'}
    
    async def delete_user_data(self, user_id: str) -> bool:
        """删除用户数据（用于数据删除权）"""
        try:
            protected_user_id = await self._protect_user_id(user_id)
            
            # 删除行为数据
            if protected_user_id in self.behavior_data:
                del self.behavior_data[protected_user_id]
            
            # 删除会话数据
            if protected_user_id in self.user_sessions:
                del self.user_sessions[protected_user_id]
            
            return True
            
        except Exception as e:
            print(f"删除用户数据失败: {e}")
            return False
    
    async def get_privacy_report(self, user_id: str) -> Dict[str, Any]:
        """获取隐私报告"""
        try:
            protected_user_id = await self._protect_user_id(user_id)
            
            report = {
                'user_id': protected_user_id,
                'data_anonymized': self.privacy_config['anonymize_user_ids'],
                'data_retention_days': self.privacy_config['data_retention_days'],
                'sensitive_fields_protected': self.privacy_config['sensitive_fields'],
                'data_exists': protected_user_id in self.behavior_data
            }
            
            if protected_user_id in self.behavior_data:
                behaviors = self.behavior_data[protected_user_id]
                oldest_data = min(b.created_at for b in behaviors) if behaviors else None
                newest_data = max(b.created_at for b in behaviors) if behaviors else None
                
                report.update({
                    'total_records': len(behaviors),
                    'oldest_record': oldest_data.isoformat() if oldest_data else None,
                    'newest_record': newest_data.isoformat() if newest_data else None,
                    'data_types_collected': list(set(b.action_type for b in behaviors))
                })
            
            return report
            
        except Exception as e:
            print(f"获取隐私报告失败: {e}")
            return {'error': '隐私报告生成失败'}
    
    async def analyze_user_segments(self, min_users: int = 5) -> Dict[str, Any]:
        """分析用户群体（聚合数据，保护隐私）"""
        try:
            if len(self.behavior_data) < min_users:
                return {'error': f'用户数量不足{min_users}人，无法进行群体分析'}
            
            segments = {
                'total_users': len(self.behavior_data),
                'user_types': defaultdict(int),
                'activity_levels': defaultdict(int),
                'feature_popularity': defaultdict(int),
                'usage_patterns': {}
            }
            
            for user_id, behaviors in self.behavior_data.items():
                if len(behaviors) < 5:  # 跳过数据不足的用户
                    continue
                
                # 分析用户类型
                user_types = await self._classify_user_type(behaviors)
                for user_type in user_types:
                    segments['user_types'][user_type] += 1
                
                # 活动水平分类
                total_actions = len(behaviors)
                if total_actions > 100:
                    segments['activity_levels']['high'] += 1
                elif total_actions > 30:
                    segments['activity_levels']['medium'] += 1
                else:
                    segments['activity_levels']['low'] += 1
                
                # 功能使用统计
                for behavior in behaviors:
                    segments['feature_popularity'][behavior.action_type] += 1
            
            # 转换为普通字典并排序
            segments['user_types'] = dict(segments['user_types'])
            segments['activity_levels'] = dict(segments['activity_levels'])
            segments['feature_popularity'] = dict(
                sorted(segments['feature_popularity'].items(), 
                      key=lambda x: x[1], reverse=True)[:10]
            )
            
            return segments
            
        except Exception as e:
            print(f"用户群体分析失败: {e}")
            return {'error': '群体分析失败'}
    
    async def get_system_usage_stats(self) -> Dict[str, Any]:
        """获取系统使用统计（聚合数据）"""
        try:
            stats = {
                'total_users': len(self.behavior_data),
                'total_actions': sum(len(behaviors) for behaviors in self.behavior_data.values()),
                'active_users_today': 0,
                'active_users_week': 0,
                'most_popular_features': [],
                'peak_usage_hours': [],
                'average_session_length': 0
            }
            
            today = datetime.now().date()
            week_ago = datetime.now() - timedelta(days=7)
            
            all_behaviors = []
            session_lengths = []
            
            for user_id, behaviors in self.behavior_data.items():
                if not behaviors:
                    continue
                
                all_behaviors.extend(behaviors)
                
                # 统计活跃用户
                user_today = any(b.created_at.date() == today for b in behaviors)
                user_week = any(b.created_at > week_ago for b in behaviors)
                
                if user_today:
                    stats['active_users_today'] += 1
                if user_week:
                    stats['active_users_week'] += 1
                
                # 估算会话长度
                if len(behaviors) > 1:
                    sorted_behaviors = sorted(behaviors, key=lambda x: x.created_at)
                    session_start = sorted_behaviors[0].created_at
                    session_end = sorted_behaviors[-1].created_at
                    session_length = (session_end - session_start).total_seconds() / 60
                    session_lengths.append(session_length)
            
            # 最受欢迎的功能
            if all_behaviors:
                action_counts = Counter(b.action_type for b in all_behaviors)
                stats['most_popular_features'] = action_counts.most_common(5)
                
                # 使用高峰时间
                hour_counts = Counter(b.created_at.hour for b in all_behaviors)
                stats['peak_usage_hours'] = hour_counts.most_common(3)
            
            # 平均会话长度
            if session_lengths:
                stats['average_session_length'] = sum(session_lengths) / len(session_lengths)
            
            return stats
            
        except Exception as e:
            print(f"获取系统使用统计失败: {e}")
            return {'error': '统计数据获取失败'}